package com.aimaoblog.admin.service;

import com.aimaoblog.admin.api.SubjectAdminService;
import com.aimaoblog.admin.dao.SubjectMapper;
import com.aimaoblog.constant.ServerResponse;
import com.aimaoblog.pojo.Subject;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author PuaChen
 * @Create 2018-07-03 17:40
 */
@Transactional(rollbackFor = Exception.class)
@Service
public class SubjectAdminServiceImpl implements SubjectAdminService {

    @Autowired
    private SubjectMapper subjectMapper;

    @Override
    public ServerResponse<PageInfo<Subject>> findAll(boolean isSplit, Integer page, Integer size) {
        if (isSplit) {
            if (page == null || size == null) {
                return ServerResponse.createFailure("参数错误");
            }
            PageHelper.startPage(page, size);
        }
        return ServerResponse.createSuccessAndData(new PageInfo<>(subjectMapper.selectAll()));
    }

    @Override
    public ServerResponse<Subject> findById(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return ServerResponse.createSuccessAndData(subjectMapper.selectByPrimaryKey(id));
    }

    @Override
    public ServerResponse<Subject> addSubject(Subject subject) {
        if (subject == null) {
            return ServerResponse.createFailure("参数错误");
        }
        subject.setId(null);
        subject.setTop(false);
        int row = subjectMapper.insertSelective(subject);
        if (row <= 0) {
            return ServerResponse.createFailure("插入失败");
        }
        return ServerResponse.createSuccess();
    }

    @Override
    public ServerResponse deleteSubject(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        int row = subjectMapper.deleteByPrimaryKey(id);
        if (row <= 0) {
            return ServerResponse.createFailure("删除失败");
        }
        return ServerResponse.createSuccess();
    }

    @Override
    public ServerResponse updateSubject(Subject subject) {
        if (subject == null || subject.getId() == null) {
            return ServerResponse.createFailure("参数错误");
        }
        int row = subjectMapper.updateByPrimaryKeySelective(subject);
        if (row <= 0) {
            return ServerResponse.createFailure("更新失败");
        }
        return ServerResponse.createSuccess();
    }
}
